import java.util.*;

/**
 * Description: 支持反向遍历List
 * Designer: jack
 * Date: 2017/9/2
 * Version: 1.0.0
 */
public class ErgodicList<T> extends ArrayList<T> {

    /*构造方法 start*/
    public ErgodicList() {
        super();
    }

    public ErgodicList(Collection<? extends T> integers) {
        super(integers);
    }
    /*构造方法 end*/

    /**
     * 反向遍历Iterator
     *
     * @return Iterable
     */
    public Iterable<T> reversed() {
        return () -> new Iterator<T>() {
            int index = ErgodicList.super.size() - 1;

            @Override
            public boolean hasNext() {
                return index > -1;
            }

            @Override
            public T next() {
                return ErgodicList.super.get(index--);
            }

//            Java8以下版本需要重写该方法
//            @Override
//            public void remove() {
//                throw new UnsupportedOperationException("remove");
//            }
        };
    }

    /**
     * 随机遍历Iterator
     *
     * @return Iterable
     */
    public Iterable<T> random() {
        return () -> {
            List<T> randomList = new ArrayList<>(this);
            Collections.shuffle(randomList, new Random());
            return randomList.iterator();
        };

    }
}
